<template>
<div class="deliveryAddressPrice">
  <y-table
    border
    :get-data-way="{data: tableData}"
    :columns="columns">
    <el-button type="primary" @click="addPrice" slot="button">添加区域定价</el-button>
    <el-table-column slot="province" label="区域" align="center" header-align="center" min-width="180">
      <template v-slot="{row}">
        <y-address-selector
          v-if="row.edit"
          v-model="row.provinceVal"
          size="mini"
          :leaf-level="2"
          show-default></y-address-selector>
        <span v-else>{{row.province ? row.province + '/' + row.city : '全部'}}</span>
      </template>
    </el-table-column>
    <el-table-column slot="startPrice" label="基本价格(元)" align="center" header-align="center" min-width="100">
      <template v-slot="{row}">
        <el-input-number v-if="row.edit" step-strictly :step="0.01" :min="0" :controls="false" v-model="row.startPrice" size="mini"></el-input-number>
        <span v-else>{{row.startPrice}}</span>
      </template>
    </el-table-column>
    <el-table-column slot="normalPrice" label="阶梯价格(元)" align="center" header-align="center" min-width="100">
      <template v-slot="{row}">
        <el-input-number v-if="row.edit" step-strictly :step="0.01" :min="0" :controls="false" v-model="row.normalPrice" size="mini"></el-input-number>
        <span v-else>{{row.normalPrice}}</span>
      </template>
    </el-table-column>
    <el-table-column slot="y-oper" label="操作" align="center" header-align="center" width="140">
      <template v-slot="{row}">
        <div class="table-buttons">
          <template v-if="!row.edit">
            <el-button type="primary" size="mini" @click="editPrice(row)">编辑</el-button>
            <el-popconfirm
                title="是否确认删除该条数据？"
                @confirm="delPrice(row)">
              <el-button slot="reference" type="danger" size="mini">删除</el-button>
            </el-popconfirm>
          </template>
          <template v-else>
            <el-button type="primary" size="mini" @click="savePrice(row)">保存</el-button>
            <el-button size="mini" @click="cancelPrice(row)">取消</el-button>
          </template>
        </div>
      </template>
    </el-table-column>
  </y-table>
</div>
</template>

<script>
export default {
  name: "deliveryAddressPrice",
  props: ['ruleId'],
  data(){
    return{
      tableData: [],
      columns: [
        {
          prop: 'province',
          template: true
        },
        {
          prop: 'startPrice',
          template: true
        },
        {
          prop: 'normalPrice',
          template: true
        }
      ],
      editing: null
    }
  },
  created(){
    this.search();
  },
  methods:{
    addPrice(){
      let newRow = {
        city: '',
        province: '',
        provinceVal: ['全部'],
        ruleId: this.ruleId,
        normalPrice: 0,
        startPrice: 0,
        edit: true
      }
      this.tableData.push(newRow);
      this.editing = newRow;
    },
    editPrice(row){
      if(!this.editing){
        this.editing = row;
        this.$set(row, 'edit', true);
      }else{
        this.$alert('存在其他正在编辑未保存的数据，请先保存其他数据再编辑本条数据', {
          confirmButtonText: '确定'
        });
      }
    },
    cancelPrice(row){
      this.editing = null;
      if(!row.id){
        let index = this.tableData.indexOf(row);
        index >= 0 && this.$delete(this.tableData, index);
      }else{
        this.$set(row, 'edit', false);
        this.$set(row, 'provinceVal', this.getProvince(row))
      }
    },
    savePrice(row){
      let data = {... row};
      this.setProvince(data.provinceVal, data);
      const unModifiedArray = this.tableData.filter(item => item !== row);
      const conflict = unModifiedArray.find(item => item.province === data.province && item.city === data.city);
      if(!!conflict){
        this.$message({
          type: 'warning',
          message: '不可保存重复的区域数据'
        });
        return;
      }
      this.$yAxios({
        url: this.$api.goods.saveDeliveryRegion,
        data,
        loading: true
      }, info => {
        this.$message({
          type: 'success',
          message: '保存成功'
        });
        this.search();
      })
    },
    delPrice(row){
      this.$yAxios({
        url: this.$api.goods.removeDeliveryRegion,
        data:{
          ids: [row.id]
        },
        loading: true
      }, info => {
        this.$message({
          type: 'success',
          message: '删除成功'
        });
        this.search();
      })
    },
    getProvince(model){
      if (!(model.province)) {
        return ['全部'];
      }
      return model.city ? [model.province, model.city] : [model.province, '全部'];
    },
    setProvince(val, model){
      if (!val || !val.length) {
        [model.province, model.city] = ['', ''];
      } else if(val[0] === '全部'){
        model.province = '';
        model.city = '';
      } else if(val[1] === '全部'){
        model.province = val[0];
        model.city = '';
      } else {
        [model.province, model.city = ''] = val;
      }
    },
    search(){
      this.$yAxios({
        url: this.$api.goods.deliveryRegionList,
        data:{
          ruleId: this.ruleId
        },
        loading: true,
      }, info => {
        this.editing = null;
        this.tableData = info.map(item => {
          this.$set(item, 'edit', false);
          this.$set(item, 'provinceVal', this.getProvince(item))
          return item;
        });
      });
    },
  }
}
</script>

<style scoped>
.deliveryAddressPrice{
  margin-top: -30px;
}
</style>